package com.yboot.starter.caffeine.core;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 本地缓存动态过期时间
 *
 * @author yangcs
 * @date 2025/8/11
 */
public class CaffeineEntryCache {

    private Cache<String, CaffeineEntry> localCache;

    public void init() {
        localCache = Caffeine.newBuilder()
                .maximumSize(50)
                .expireAfter(new CustomExpiry())
                .build();
    }

    public void setLocalCache(String key, Object object, boolean accessFresh){
        CaffeineEntry caffeineEntry = new CaffeineEntry();
        caffeineEntry.setKey(key);
        caffeineEntry.setValue(object);
        caffeineEntry.setExpireTime(TimeUnit.MINUTES.toNanos(30));
        caffeineEntry.setAccessFresh(accessFresh);
        localCache.put(key, caffeineEntry);
    }

    /***
     * 返回值 如果不存在返回null
     * @param key
     * @param <T>
     * @return
     */
    public <T> T getCache(String key){
        CaffeineEntry caffeineEntry = localCache.getIfPresent(key);
        if (Objects.nonNull(caffeineEntry)) {
            return (T) caffeineEntry.getValue();
        }
        return null;
    }

    public void remove(String key){
        localCache.invalidate(key);
    }
}
